<?php
App::uses('AppController', 'Controller');
/**
 * Productsinstances Controller
 *
 * @property Productsinstance $Productsinstance
 */
class ProductsinstancesController extends AppController {

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Productsinstance->recursive = 0;
		$productsinstances = $this->Productsinstance->find('all', array('conditions' => array('Productsinstance.archive' => '0')));
		$this->set(compact('productsinstances'));

		$this->loadModel('Productsbrands');
		$brands = $this->Productsbrands->find('all');
		$brand = array();
		foreach($brands as $i=>$j){
			$brand = Set::insert($brand, $j['Productsbrands']['id'], $j['Productsbrands']['name']);
		}

		$this->loadModel('Productsranges');
		$ranges = $this->Productsranges->find('all');
		$range = array();
		foreach($ranges as $i=>$j){
			$range = Set::insert($range, $j['Productsranges']['id'], $j['Productsranges']['name']);
		}

		$this->loadModel('Productscategories');
		$categories = $this->Productscategories->find('all');
		$category = array();
		foreach($categories as $i=>$j){
			$category = Set::insert($category, $j['Productscategories']['id'], $j['Productscategories']['name']);
		}

		$this->set(compact('brand', 'range', 'category'));
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Productsinstance->exists($id)) {
			throw new NotFoundException(__('Invalid productsinstance'));
		}
		$options = array('conditions' => array('Productsinstance.' . $this->Productsinstance->primaryKey => $id));
		$this->set('productsinstance', $this->Productsinstance->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Productsinstance->create();
                        //print_r($this->data);
			if ($this->Productsinstance->save($this->request->data)) {
				$this->Session->setFlash(__('The product Instance has been saved'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The product Instance could not be saved. Please, try again.'),'default', array('class' => 'saveerror'));
			}
		}
             $removalreasons = $this->Productsinstance->Removalreason->find('list',array('order'=>'name ASC'));
             $products = $this->Productsinstance->Product->find('list', array('order'=>'id ASC'));
             $this->set(compact('products','removalreasons'));;
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Productsinstance->exists($id)) {
			throw new NotFoundException(__('Invalid productsinstance'));
		}
		$productsinstance = $this->Productsinstance->findById($id);
		if ($this->request->is('post') || $this->request->is('put')) {

			$oriNum = $productsinstance['Productsinstance']['number_removed'];
			$changes = $oriNum - $this->request->data['Productsinstance']['number_removed'];

			$data = array('id'=>$productsinstance['Product']['id'], 'onhand_level'=>$productsinstance['Product']['onhand_level']+$changes);

			if($this->Productsinstance->Product->save($data)){
				$data = $this->request->data['Productsinstance'];
				if($this->Productsinstance->save($data)){
					$this->Session->setFlash(__('The products used has been saved'),'default', array('class' => 'savesuccess'));
					$this->redirect(array('action' => 'index'));
				}
			}
			else{
				$this->Session->setFlash(__('The products used could not be saved. Please, try again.'),'default', array('class' => 'saveerror'));
			}
		}
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$removalreasons = $this->Productsinstance->Removalreason->find('list');
			
		$brand = $this->Productsbrands->findById($productsinstance['Product']['productsbrands_id']);
		$productsinstance = Set::insert($productsinstance, 'Brands', $brand['Productsbrands']);
		
		$ranges = $this->Productsranges->findById($productsinstance['Product']['productsranges_id']);
		$productsinstance = Set::insert($productsinstance, 'Ranges', $ranges['Productsranges']);
		
		$categories = $this->Productscategories->findById($productsinstance['Product']['productscategories_id']);
		$productsinstance = Set::insert($productsinstance, 'Categories', $categories['Productscategories']);

		$this->set(compact('removalreasons', 'productsinstance'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @throws MethodNotAllowedException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Productsinstance->id = $id;
		if (!$this->Productsinstance->exists()) {
			throw new NotFoundException(__('Invalid productsinstance'));
		}
		$this->request->onlyAllow('post', 'delete');
		$data = array('id' => $id, 'archive' => '1');
		if ($this->Productsinstance->save($data)) {
			$this->Session->setFlash(__('Productsinstance deleted'),'default', array('class' => 'savesuccess'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Productsinstance was not deleted'),'default', array('class' => 'saveerror'));
		$this->redirect(array('action' => 'index'));
	}

/**
 * choosesupplier method
 *
 * @return void
 */
	public function choosesupplier() {
		if ($this->request->is('post')) {
			//print_r($this->data);
			$this->redirect(array('action' => 'record',$this->data['productsinstances']['suppliers_id']));
		}
		$this->loadModel('Suppliers');
		$supplier = $this->Suppliers->find('all',array('conditions' => array('archive' => '0')));
		$suppliers = array();
		foreach($supplier as $i=>$j){
			$suppliers = Set::insert($suppliers, $j['Suppliers']['id'], $j['Suppliers']['supplierName']);
		}
		//print_r($suppliers);
		$this->Set(compact('suppliers'));
	}

/**
 * record method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function record($id = null) {
		if ($this->request->is('post')) {
			//print_r($this->data);
			
			//check if there is any quantity used
			$empty = false;
			foreach($this->data['Quantity Used'] as $i => $j):
				if(!empty($this->data['Quantity Used'][$i])){
					$empty = true;
				}
			endforeach;
			
			if(!$empty){
				$this->Session->setFlash(__('Products used was not recorded because there was quantity used.'),'default', array('class' => 'saveerrors'));
				$this->redirect(array('action' => 'index'));
			}
			else{
				//save each products instances
				foreach($this->data['productsinstances'] as $i => $j):
					if(!empty($this->data['Quantity Used'][$i])){
						$data = array(	'products_id' 		=> $j,
										'doc'				=> date('d/m/Y'),
										'number_removed'	=> $this->data['Quantity Used'][$i],
										'removalReasons_id'	=> $this->data['Removal Reason'][$i]);
						$this->Productsinstance->create();
						print_r($data);
						if($this->Productsinstance->save($data)){
							
							//decrease product on_hand level
							$product = $this->Productsinstance->Product->findById($j);
							$num = $product['Product']['onhand_level'] - $this->data['Quantity Used'][$i];
							if($num < 0){ $num = 0; }
							$data = array(	'id' => $j, 
											'onhand_level' => $num);
							//print_r($data);
							$this->Productsinstance->Product->save($data);

						}


					}
				endforeach;

				$this->Session->setFlash(__('Product used has been recorded'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'index'));
			}
			
		}
		
		$this->loadModel('Suppliers');
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$suppliers = $this->Suppliers->findById($id);
		$this->set(compact('suppliers'));
		//print_r($suppliers);

		$products = $this->Productsinstance->Product->find('all', array('conditions'=>array('suppliers_id' => $id,
																							'archive' => '0')));
		//$this->set(compact('products'));
		//print_r($products);
		

		foreach ($products as $i => $j) {
			
			$brand = $this->Productsbrands->findById($j['Product']['productsbrands_id']);
			$products = Set::insert($products, $i.'.Brands', $brand['Productsbrands']);
			
			$ranges = $this->Productsranges->findById($j['Product']['productsranges_id']);
			if(empty($ranges)){$ranges = array('Productsranges' => array('name' => ''));}
			$products = Set::insert($products, $i.'.Ranges', $ranges['Productsranges']);
			
			$categories = $this->Productscategories->findById($j['Product']['productscategories_id']);
			if(empty($categories)){$categories = array('Productscategories' => array('name' => ''));}
			$products = Set::insert($products, $i.'.Categories', $categories['Productscategories']);
		}

		$this->set(compact('products'));
		//print_r($products);

		$removalreason = $this->Productsinstance->Removalreason->find('all', array('conditions' => array('archive' => '0')));
		$removalreasons = array();
		foreach($removalreason as $i=>$j){
			$removalreasons = Set::insert($removalreasons, $j['Removalreason']['id'], $j['Removalreason']['name']);
		}
		$this->set(compact('removalreasons'));
		//print_r($removalreasons);
	}

/**
 * recordbarcode method
 *
 * @return void
 */
	public function recordbarcode() {
		$this->loadModel('Productsbrands');
		$this->loadModel('Productsranges');
		$this->loadModel('Productscategories');

		$rr = $this->Productsinstance->Removalreason->findByName('Salon Used');
		$products = array();
		$qu = array();

		if ($this->request->is('post')) {
		//print_r($this->data);

			//check if the user wants to add many product used
			if(!empty($this->request->data['onepi']['barcode'])){

				$product = $this->Productsinstance->Product->find('first', array('conditions' => array('Product.barcode' => $this->request->data['onepi']['barcode'])));
				
				if(!empty($product)){

					$lastindex = 0;
					if(!empty($this->request->data['products'])){
						foreach($this->request->data['products'] as $i=>$j){
							$p = $this->Productsinstance->Product->findById($j);
							$products = Set::insert($products, $i.'.Product', $p['Product']);
							if(!empty($this->request->data['Quantity Used'][$i])){
								$qu = Set::insert($qu, $i, $this->request->data['Quantity Used'][$i]);
							} else {
								$qu = Set::insert($qu, $i, 1);
							}
							$lastindex++;
						}
					}

					$products = Set::insert($products, $lastindex.'.Product', $product['Product']);
					$qu = Set::insert($qu, $lastindex, 1);

				} else {
					$this->Session->setFlash(__('The product could not be found. Please, try again.'),'default', array('class' => 'saveerror'));
				}
			} else {
				//save each products instances
				foreach($this->data['products'] as $i => $j):
					if(!empty($this->data['Quantity Used'][$i])){
						$data = array(	'products_id' 		=> $j,
										'doc'				=> date('d/m/Y'),
										'number_removed'	=> $this->data['Quantity Used'][$i],
										'removalReasons_id'	=> $rr['Removalreason']['id']);
						$this->Productsinstance->create();
						print_r($data);
						if($this->Productsinstance->save($data)){
							//decrease product on_hand level
							$product = $this->Productsinstance->Product->findById($j);
							$num = $product['Product']['onhand_level'] - $this->data['Quantity Used'][$i];
							if($num < 0){ $num = 0; }
							$data = array(	'id' => $j, 
											'onhand_level' => $num);
							//print_r($data);
							$this->Productsinstance->Product->save($data);
						}
					}
				endforeach;

				$this->Session->setFlash(__('Product used has been recorded'),'default', array('class' => 'savesuccess'));
				$this->redirect(array('action' => 'index'));

			}
		}

		if(!empty($products)){

			foreach ($products as $i => $j) {
				$brand = $this->Productsbrands->findById($j['Product']['productsbrands_id']);
				$products = Set::insert($products, $i.'.Brands', $brand['Productsbrands']);
				
				$ranges = $this->Productsranges->findById($j['Product']['productsranges_id']);
				if(empty($ranges)){$ranges = array('Productsranges' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Ranges', $ranges['Productsranges']);
				
				$categories = $this->Productscategories->findById($j['Product']['productscategories_id']);
				if(empty($categories)){$categories = array('Productscategories' => array('name' => ''));}
				$products = Set::insert($products, $i.'.Categories', $categories['Productscategories']);
			}

		}

		$this->set(compact('products', 'qu'));

	}
}
